package com.uml.youmath;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

public class SoundService {
	static MediaPlayer musicPlayer = null;
	static SoundPool soundPool = null; 
	static int MUSIC = 0, CHEERS = 1, BOO = 2;
	static int currentPos = 0;

	static HashMap<Integer, Integer> soundPoolMap;

	public static void initSounds(Context context) {
	     soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
	     soundPoolMap = new HashMap<Integer, Integer>();
	     soundPoolMap.put(CHEERS, soundPool.load(context, R.raw.crowd_cheers, 1));
	     soundPoolMap.put(BOO, soundPool.load(context, R.raw.crowd_boo, 1));
	}
	          
	public static void playSound(Context context, int soundType) {
	    AudioManager mgr = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
	    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
	    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
	    float volume = streamVolumeCurrent / streamVolumeMax;
	    
	    soundPool.play(soundPoolMap.get(soundType), volume, volume, 1, 0, 1f);     
	}

	public static void start(Context context, int soundType) {
		if (soundType == MUSIC) {
			musicPlayer = MediaPlayer.create(context, R.raw.background_music);
			musicPlayer.setLooping(true);
		}
		if (currentPos > 0) {
			resumeAt();
		}
		musicPlayer.start();
	}

	public static void resumeAt() {
		musicPlayer.seekTo(currentPos);
		if (!musicPlayer.isPlaying()) {
			musicPlayer.start();
		}
	}

	public static void pause() {
		currentPos = musicPlayer.getCurrentPosition();
		musicPlayer.pause();
	}

	public static void stopSoundEffects() {
		soundPool.autoPause();
	}
	
	public static void resumeSoundEffects() {
		soundPool.autoResume();
	}
}